import { ref } from "vue";
import { defineStore } from 'pinia';
import axios from "axios";

export const useAuthStore = defineStore('auth', () => {
    const jwt = ref<string>(); // JWT 默认值为 undefined

    function getJwt() {
        if (jwt.value === undefined) {
            const token = localStorage.getItem('jwt'); // 从 localStorage 初始化
            if (token) {
                jwt.value = token;
            }
        }
        return jwt.value;
    }

    function setJwt(token: string) {
        jwt.value = token;
        localStorage.setItem('jwt', token); // 持久化存储
    }

    function clearJwt() {
        jwt.value = undefined;
        localStorage.removeItem('jwt'); // 清除持久化存储
    }

    async function isLoggedIn(): Promise<boolean> {
        if (getJwt() === undefined)
            return false;

        try {
            // 发送带 JWT 的 POST 请求，以验证登录是否有效
            const response = await axios({
                method: 'get',
                url: 'http://192.168.101.15:18080/api/auth',
                headers: {
                    Authorization: `Bearer ${jwt.value}`,
                },
            });
            return response.status === 200;
        } catch (e) {
            // 验证失败，清除 JWT
            clearJwt()
            return false;
        }
    }

    return {
        getJwt,
        setJwt,
        clearJwt,
        isLoggedIn
    };
});